package com.atguigu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.edu.entity.EduSubject;
import com.atguigu.edu.entity.ExcelSubject;
import com.atguigu.edu.service.EduSubjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author ：HB
 * @date ：Created in 2020/11/7 12:34
 * @description：easyExcel的读操作的监听类
 *
 * @Component交给spring管理，让spring发现
 */
@Component
public class MySubjectListener extends AnalysisEventListener<ExcelSubject> {

    @Autowired
    private EduSubjectService eduSubjectService;
    /**
     * 一行一行的读取数据，将读取的数据插入到数据库中
     * @param excelSubject excel表格对象
     * @param analysisContext
     */
    @Override
    public void invoke(ExcelSubject excelSubject, AnalysisContext analysisContext) {
        //获取到父类的节点 读取到的数据分为两列 一级分类  二级分类
        String parentSubjectName = excelSubject.getParentSubjectName();
        //保存一级分类 需要判断DB是否存在 parentId=0
        EduSubject parentSubject = eduSubjectService.existSubject(parentSubjectName, "0");
        if (parentSubject == null) {
            //数据库中不存在那一行数据
            parentSubject= new EduSubject();
            parentSubject.setTitle(parentSubjectName);
            parentSubject.setParentId("0");
            eduSubjectService.save(parentSubject);
        }
        //保存二级分类 需要判断DB是否存在 parentId=一级分类的id
        //excelSubject.getChildSubjectName()：当前一级对象对应的二级对象的名字 与id
        String childSubjectName = excelSubject.getChildSubjectName();
        String parentSubjectId = parentSubject.getId();
        EduSubject childSubject = eduSubjectService.existSubject(childSubjectName, parentSubjectId);
        if (childSubject == null) {
            //数据库中不存在那一行数据
            childSubject= new EduSubject();
            childSubject.setTitle(childSubjectName);
            childSubject.setParentId(parentSubjectId);
            eduSubjectService.save(childSubject);
        }

    }

    //读取成功之后调用这个函数
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
